﻿
namespace ExtPageBuilder
{
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using Ext.Net;
    /// <summary>
    /// Description: DynamicControl dùng đề hổ trợ việc Build các control EXT trên giao diện 
    ///             từ động dựa vào thông tin table được lưu trong DB.
    /// Author : SONNT12.
    /// CreateDate:30/05/2012.
    /// Last date modify: 31/05/2012.
    /// </summary>
    public class DynamicExtControl
    {
        private List<Object_info> page_info;

        public List<Object_info> Page_info
        {
            get { return page_info; }
            set { page_info = value; }
        }
        public DynamicExtControl()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// Dùng để convert ObjectProperty của table sang JSON.
        /// </summary>
        /// <param name="tabname">Tên table</param>
        /// <param name="langID">Mã ngôn ngữ hiện thị.</param>
        /// <returns>JSON của ObjectProperty</returns>
        public string GetObjectProperty(string tabname, string langID, params object[] options)
        {
            string jsonObj = string.Empty;

            int option = 0;
            if (options != null)
            {
                //if (options.Count() > 1)
                if (options.Count() > 0)
                {
                    option = (int)options[0];
                }
            }

            List<Object_info> objectinfo = new List<Object_info>();
            switch (option)
            {
                case 1:
                    objectinfo = (from d in this.page_info
                                  where d.Name.ToLower().Trim() == tabname.ToLower().Trim() && d.Show_in_list.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
                case 2:
                    objectinfo = (from d in this.page_info
                                  where d.Name.ToLower().Trim() == tabname.ToLower().Trim() && d.Show_in_lookup.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
                case 3:
                    objectinfo = (from d in this.page_info
                                  where d.Name.ToLower().Trim() == tabname.ToLower().Trim() && d.Show_in_grid.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
                default:
                    objectinfo = (from d in this.page_info
                                  where d.Name.ToLower().Trim() == tabname.ToLower().Trim() && d.Show_in_list.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
            }

            //List<Object_info> objectinfo = (from d in this.page_info
            //                                //dailt where d.Name.ToLower().Trim() == tabname.ToLower().Trim() && d.Show_in_grid == true
            //                                where d.Name.ToLower().Trim() == tabname.ToLower().Trim() && d.Show_in_list == true
            //                                orderby d.Grid_order
            //                                select d).ToList();
            for (int i = 0; i < objectinfo.Count; i++)
            {
                Object_info oinfo = objectinfo[i];
                string fLabel = oinfo.Caption;
                if (!string.IsNullOrEmpty(oinfo.Caption_ML))
                {
                    JsonObject objText = JSON.Deserialize<JsonObject>(oinfo.Caption_ML);
                    fLabel = objText[langID].ToString();
                }
                jsonObj = jsonObj + string.Format("{{'FIELD':'{0}','VALUE':'{1}'}},", fLabel, Name2ID(oinfo.Property_name));
            }
            jsonObj = "[" + jsonObj.Trim().Trim(',') + "]";
            return jsonObj;
        }
        public object SetDefaultValue(string tabname, object obj)
        {
            string jsonObj = string.Empty;
            List<Object_info> objectinfo = (from d in this.page_info
                                            where d.Name.ToLower().Trim() == tabname.ToLower().Trim() && d.Show_in_grid == true
                                            orderby d.Grid_order
                                            select d).ToList();
            for (int i = 0; i < objectinfo.Count; i++)
            {
                Object_info oinfo = objectinfo[i];
                if (!string.IsNullOrEmpty(oinfo.Init_value))
                {
                    //obj.GetType().GetProperty(Name2ID(oinfo.Property_name)).SetValue(obj, oinfo.Init_value);
                }
            }
            return obj;
        }
        public void SetDefaultValue(string tabname, object currentClass, Ext.Net.ResourceManager rem)
        {
            try
            {
                string jsonObj = string.Empty;
                List<Object_info> objectinfo = (from d in this.page_info
                                                where d.Name.ToLower().Trim() == tabname.ToLower().Trim() && d.Show_in_grid == true && d.Init_value != null
                                                orderby d.Grid_order
                                                select d).ToList();
                for (int i = 0; i < objectinfo.Count; i++)
                {
                    Object_info oinfo = objectinfo[i];
                    if (!string.IsNullOrEmpty(oinfo.Init_value))
                    {
                        if (oinfo.Init_value.StartsWith("@"))
                        {
                            object value = currentClass.GetType().GetProperty(oinfo.Init_value.Trim('@')).GetValue(currentClass, null);
                            rem.RegisterOnReadyScript(string.Format("Ext.getCmp('{0}').setValue('{1}');", Name2ID(oinfo.Property_name), value));

                        }
                        else
                            rem.RegisterOnReadyScript(string.Format("Ext.getCmp('{0}').setValue('{1}');", Name2ID(oinfo.Property_name), currentClass, oinfo.Init_value));
                    }
                }
            }
            catch
            {

            }

        }

        //public void Buil_Report(FormLayout formlayouts, string tablename, string langID)
        //{

        //    List<Object_info> objectinfo = (from d in this.page_info
        //                                    where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_form.Value == true
        //                                    orderby d.Form_tab_index
        //                                    select d).ToList();

        //    for (int i = 0; i < objectinfo.Count; i++)
        //    {
        //        Object_info o = objectinfo[i];
        //        Field _f = Buil_control(o, langID, false);
        //        _f.Name = _f.ID.Trim('@');
        //        _f.ID = _f.ID.Trim('@');
        //        if (_f == null)
        //            continue;
        //        if (formlayouts.Anchors.SingleOrDefault(a => a.Control.ID == _f.ID) == null)
        //        {
        //            Anchor _achor = new Anchor(_f);
        //            set_FieldWidth(o, _f, _achor);
        //            formlayouts.Anchors.Add(_achor);
        //        }
        //    }

        //}

        /// <summary>
        /// Dùng để Build Form không có chứa TabPanel.
        /// </summary>
        /// <param name="formlayouts">Cung cấp List formlayout để add control vào.</param>
        /// <param name="tablename">Tên table cần lấy thông tin.</param>
        /// <param name="langID">Mã ngôn ngữ hiện thị.</param>
        //public void Buil_form(List<FormLayout> formlayouts, string tablename, string langID)
        //{

        //    List<Object_info> objectinfo = (from d in this.page_info
        //                                    where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_form.Value == true
        //                                    orderby d.Form_tab_index
        //                                    select d).ToList();
        //    int countinform = (int)Math.Ceiling((double)objectinfo.Count / formlayouts.Count);

        //    for (int i = 0; i < objectinfo.Count; i++)
        //    {
        //        Object_info o = objectinfo[i];
        //        Field _f = Buil_control(o, langID, false);
        //        if (_f == null)
        //            continue;
        //        if (formlayouts[(int)i / countinform].Anchors.SingleOrDefault(a => a.Control.ID == _f.ID) == null)
        //        {
        //            Anchor _achor = new Anchor(_f);
        //            set_FieldWidth(o, _f, _achor);
        //            formlayouts[(int)i / countinform].Anchors.Add(_achor);
        //        }
        //    }

        //}

        /// <summary>
        /// Cập nhật độ rộng phù hợp cho file
        /// </summary>
        /// <param name="o">thông tin field</param>
        /// <param name="_f">field </param>
        /// <param name="_achor">Anchor</param>
        public void set_FieldWidth(Object_property o, Field _f)
        {
            if (o.Data_length != null)
            {
                if (o.Data_length.Value > 50)
                    _f.Anchor = "100%";
                else
                {
                    if (_f.GetType() == typeof(Checkbox) || _f.GetType() == typeof(Radio))
                        return;
                    _f.InputWidth = (o.Data_length.Value * 5 < 100 ? 100 : o.Data_length.Value * 5) + 5;
                }

            }
        }

        /// <summary>
        /// Dùng để Build FormLayout.
        /// </summary>
        /// <param name="count">Cung cấp số lượng FormLayout cần  tạo.</param>
        /// <param name="index">Chỉ số index dùng tạo tên cho ID control được unique.</param>
        /// <returns>List of FormLayouts.</returns>
        public List<FormPanel> Buil_FormLayout(int count, int index)
        {
            List<FormPanel> FormLayoutList = new List<FormPanel>();
            for (int i = 0; i < count; i++)
            {
                FormPanel objFormLayout = new FormPanel();
                objFormLayout.ID = "FormPanel" + index.ToString() + i.ToString();
                objFormLayout.IDMode = IDMode.Static;
                objFormLayout.Flex = 1;
                objFormLayout.Anchor = "100";
                objFormLayout.BodyBorder = 0;
                objFormLayout.Border = false;
                objFormLayout.Padding = 4;
                objFormLayout.TrackResetOnLoad = true;
                FormLayoutList.Add(objFormLayout);
            }
            return FormLayoutList;
        }




        /// <summary>
        /// Dùng để Build Grid.
        /// </summary>
        /// <param name="grd"> Đối tượng GridPanel truyền từ giao diện.</param>
        /// <param name="tablename">Tên table cần lấy thông tin.</param>
        /// <param name="langID">Mã ngôn ngữ hiện thị.</param>
        /// <param name="editable">Cho phép edit</param>
        public void Buil_grid(ref GridPanel grd, string tablename, string langID, bool editable, params object[] options)
        {
            int option = 0;
            if (options != null)
            {
                //if (options.Count() > 1)
                if (options.Count() > 0)
                {
                    option = (int)options[0];
                }
            }

            List<Object_info> objectinfo = new List<Object_info>();
            switch (option)
            {
                case 1:
                    objectinfo = (from d in this.page_info
                                  where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_list.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
                case 2:
                    objectinfo = (from d in this.page_info
                                  where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_lookup.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
                default:
                    objectinfo = (from d in this.page_info
                                  where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_grid.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
            }

            foreach (Object_info o in objectinfo)
            {
                //ColumnBase _c = Buil_grid_column(o, langID, editable);
                //if (_c == null)
                //    continue;
                //if (grd.ColumnModel.Columns.SingleOrDefault(c => c.ColumnID == _c.ColumnID) == null)
                //    grd.ColumnModel.Columns.Add(_c);
                //if (grd.View.Count > 0)
                //{
                //    if (grd.View[0].HeaderRows.Count > 0)
                //    {
                //        HeaderColumn _h = new HeaderColumn();
                //        Field hf = Buil_control(o, langID, true, new string[] { "HDF" });
                //        hf.ID += "Filter";
                //        // hf.FieldLabel = "";
                //        string ff = "applyFilter";
                //        if (options != null)
                //        {
                //            //if (options.Count() > 1)
                //            if (options.Count() > 1)
                //            {
                //                ff = options[1].ToString();

                //                if (hf.GetType() == typeof(Ext.Net.TextField))
                //                {
                //                    ((Ext.Net.TextField)hf).EnableKeyEvents = true;
                //                }
                //                hf.AddListener("keyup", ff);
                //            }
                //        }
                //        hf.AddListener("change", ff);
                //        _h.Component.Add(hf);
                //        grd.View[0].HeaderRows[0].Columns.Add(_h);
                //    }
                //}
            }
            //if (grd.View.Count > 0)
            //{
            //    if (grd.View[0].HeaderRows.Count > 0)
            //    {
            //        CommandColumn _cl = new CommandColumn();
            //        _cl.Width = 30;
            //        _cl.ColumnID = "clClearFilter";

            //        grd.ColumnModel.Columns.Add(_cl);
            //        HeaderColumn _hl = new HeaderColumn();
            //        Button clearFilter = new Button();
            //        clearFilter.ID = "btnClearFilter";
            //        clearFilter.Icon = Icon.Decline;
            //        clearFilter.Listeners.Click.Handler += "clearFilter();";
            //        _hl.Component.Add(clearFilter);
            //        grd.View[0].HeaderRows[0].Columns.Add(_hl);
            //    }
            //}

        }

        /// <summary>
        /// Dùng để Build Grid.
        /// </summary>
        /// <param name="sto">Cung cấp Store</param>
        /// <param name="tablename">Tên table cần lấy thông tin.</param>
        /// <param name="langID">Mã ngôn ngữ hiện thị.</param>
        public void Buil_store(ref Store sto, string tablename, string langID, params object[] options)
        {
            int option = 0;
            if (options != null)
            {
                //if (options.Count() > 1)
                if (options.Count() > 0)
                {
                    option = (int)options[0];
                }
            }

            List<Object_info> objectinfo = new List<Object_info>();
            switch (option)
            {
                case 1:
                    objectinfo = (from d in this.page_info
                                  //where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_grid.Value == true
                                  //view form use Show_in_form
                                  where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_list.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
                case 2:
                    objectinfo = (from d in this.page_info
                                  //where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_grid.Value == true
                                  //view form use Show_in_form
                                  where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_lookup.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
                case 3:
                    objectinfo = (from d in this.page_info
                                  //where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_grid.Value == true
                                  //view form use Show_in_form
                                  where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_grid.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
                default:
                    objectinfo = (from d in this.page_info
                                  //where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_grid.Value == true
                                  //view form use Show_in_form
                                  where d.Name.ToLower().Trim() == tablename.ToLower().Trim() && d.Show_in_form.Value == true
                                  orderby d.Grid_order
                                  select d).ToList();
                    break;
            }

            //RecordField _fk = new RecordField();
            //_fk.Type = RecordFieldType.String;
            //_fk.Name = "Key";
            //sto.Reader.Reader.Fields.Add(_fk);
            //foreach (Object_info o in objectinfo)
            //{
            //    RecordField _f = Buil_recordfield(o, langID);
            //    if (_f == null)
            //        continue;
            //    if (sto.Reader.Reader.Fields.SingleOrDefault(f => f.Name == _f.Name) == null)
            //        sto.Reader.Reader.Fields.Add(_f);
            //}

        }

        /// <summary>
        /// Dùng để Build RecordField.
        /// </summary>
        /// <param name="oinfo">Cung cấp Object được lấy từ DB để tạo RecordField. </param>
        /// <param name="langID">Mã ngôn ngữ hiện thị.</param>
        /// <returns>RecordField</returns>
        public ModelField Buil_recordfield(Object_property oinfo, string langID)
        {
            ModelField field = new ModelField();
            string type = string.IsNullOrEmpty(oinfo.Control_addIn) ? oinfo.Name.Trim().ToLower() : oinfo.Control_addIn.Trim().ToLower();
            switch (type)
            {

                case "decimal":
                case "float":
                case "double":
                    field.Type = ModelFieldType.Float;
                    field.DefaultValue = "0";

                    break;
                case "int":
                case "bigint":
                case "smallint":
                case "tinyint":
                    field.Type = ModelFieldType.Int;
                    field.DefaultValue = "0";
                    break;
                case "boolean":
                    field.Type = ModelFieldType.Boolean;
                    field.DefaultValue = "0";
                    break;
                case "datetime":
                case "date":
                    field.Type = ModelFieldType.Date;
                    break;
                default:
                    field.DefaultValue = "";
                    break;
            }
            if (field != null)
            {
                field.Name = Name2ID(oinfo.Name);
                field.SubmitEmptyValue = EmptyValue.Null;
                field.UseNull = true;
            }
            return field;
        }

        /// <summary>
        /// Dùng để Build Field.
        /// </summary>
        /// <param name="oinfo">Cung cấp Object được lấy từ DB để tạo Field. </param>
        /// <param name="langID">Mã ngôn ngữ hiện thị.</param>
        /// <returns>Field</returns>
        public Field Buil_control(Object_property oinfo, string langID, bool inGrid, params string[] arg)
        {
            bool isHeaderFilter = false;
            if (arg != null && arg.Length > 0 && arg[0] == "HDF")
            {
                isHeaderFilter = true;
            }
            CultureInfo cinfo = new CultureInfo(Convert.ToInt32(langID));
            string fLabel = oinfo.Caption.Replace('_', '.');
            if (!string.IsNullOrEmpty(oinfo.Caption_ML))
            {
                JsonObject objText = JSON.Deserialize<JsonObject>(oinfo.Caption_ML);
                fLabel = objText[langID].ToString();
            }
            Field field = null;

            if (oinfo.Look_up_page != null)
            {
                TriggerField tg = new TriggerField();
                FieldTrigger.Config cof = new FieldTrigger.Config();

                //Classes.Menu menu = GB_Vars.GMenuList.SingleOrDefault(m => m.ID == oinfo.Look_up_page.Value);


                //string fnTriggerClick = string.Empty;
                //if (menu != null)
                //{
                //    string url = menu.Url;
                //    if (!string.IsNullOrEmpty(oinfo.Extended_info) && oinfo.Extended_info.Contains("query"))
                //    {
                //        oinfo.Extended_info = "{" + oinfo.Extended_info.TrimStart('{').TrimEnd('}') + "}";
                //        JsonObject oc = JSON.Deserialize<JsonObject>(oinfo.Extended_info);
                //        if (oc.ContainsKey("query"))
                //        {
                //            //url += "&filter=" + oc["query"];
                //            url += "&filter=" + Uri.EscapeUriString(oc["query"].ToString());

                //        }

                //    }
                //    fnTriggerClick = string.Format("Lookup(item, trigger, index, e,'{0}') ;", url);
                //    tg.Listeners.TriggerClick.Handler += fnTriggerClick;
                //}

                cof.Icon = TriggerIcon.Search;
                tg.Triggers.Add(new FieldTrigger(cof));
                tg.EnableKeyEvents = true;
                if (!isHeaderFilter)
                    tg.AllowBlank = !oinfo.Not_blank.Value;
                if (oinfo.Data_length != null)
                {

                    tg.MaxLength = oinfo.Data_length.Value;
                }
                if (oinfo.Data_length != null)
                {

                    tg.MaxLength = oinfo.Data_length.Value;
                }
                tg.SelectOnFocus = true;
                tg.Listeners.KeyUp.Handler += "ShortcutKeyTrigger(item,e);";
                field = tg;

            }
            else
            {
                string type = string.IsNullOrEmpty(oinfo.Control_addIn) ? oinfo.Type.Trim().ToLower() : oinfo.Control_addIn.Trim().ToLower();
                switch (type)
                {
                    case "nvarchar":
                    case "varchar":
                    case "char":
                        if (!oinfo.Editable.Value & !isHeaderFilter)
                        {
                            DisplayField dp = new DisplayField();
                            field = dp;
                        }
                        else
                        {
                            TextField ct = new TextField();
                            if (!isHeaderFilter)
                                ct.AllowBlank = !oinfo.Not_blank.Value;
                            if (oinfo.Data_length != null)
                            {

                                ct.MaxLength = oinfo.Data_length.Value;
                            }
                            if (oinfo.Data_length != null)
                            {

                                ct.MaxLength = oinfo.Data_length.Value;
                            }
                            ct.SelectOnFocus = true;
                            field = ct;
                        }
                        break;
                    case "decimal":
                    case "float":
                    case "double":
                        //ct2.ClearCls = "x-form-clear-right";
                        if (!oinfo.Editable.Value & !isHeaderFilter)
                        {
                            DisplayField dp = new DisplayField();
                            field = dp;
                        }
                        else
                        {
                            NumberField nf = new NumberField();
                            if (!isHeaderFilter)
                                nf.AllowBlank = !oinfo.Not_blank.Value;
                            if (!string.IsNullOrEmpty(oinfo.Min_value))
                            {
                                nf.MinValue = double.Parse(oinfo.Min_value);
                            }
                            if (!string.IsNullOrEmpty(oinfo.Max_value))
                            {
                                nf.MaxValue = double.Parse(oinfo.Max_value);
                            }
                            if (oinfo.Decimal_places != null)
                            {
                                nf.DecimalPrecision = oinfo.Decimal_places.Value;
                            }

                            nf.SelectOnFocus = true;
                            field = nf;
                        }
                        if ((!inGrid && oinfo.Editable.Value) | isHeaderFilter)
                        {
                            TextField ct2 = new TextField();


                            if (isHeaderFilter)
                            {
                                ct2.MaskRe = string.Format("/[0-9-<>={0}{{1}}]/", cinfo.NumberFormat.CurrencyDecimalSeparator);
                            }
                            else
                            {
                                ct2.MaskRe = string.Format("/[0-9-{0}{{1}}]/", cinfo.NumberFormat.CurrencyDecimalSeparator);
                                ct2.Listeners.Change.Handler = "this.setValue(formatMoneyWhenChange(newValue));";
                            }
                            //string format = "0" + cinfo.NumberFormat.CurrencyGroupSeparator + "000" + cinfo.NumberFormat.CurrencyDecimalSeparator + "00/i";

                            //ct2.Listeners. = "this.setValue(Ext.util.Format.number(item.getValue(),'" + format + "'));";
                            if (!isHeaderFilter)
                                ct2.AllowBlank = !oinfo.Not_blank.Value;
                            if (oinfo.Data_length != null)
                            {

                                ct2.MaxLength = oinfo.Data_length.Value;
                            }
                            if (oinfo.Data_length != null)
                            {

                                ct2.MaxLength = oinfo.Data_length.Value;
                            }
                            ct2.SelectOnFocus = true;
                            field = ct2;

                        }
                        break;
                    case "int":
                    case "bigint":
                    case "smallint":
                    case "tinyint":
                        if (!oinfo.Editable.Value & !isHeaderFilter)
                        {
                            DisplayField dp = new DisplayField();
                            field = dp;
                        }
                        else
                        {
                            NumberField nf2 = new NumberField();
                            if (!isHeaderFilter)
                                nf2.AllowBlank = !oinfo.Not_blank.Value;
                            nf2.AllowDecimals = false;
                            if (!string.IsNullOrEmpty(oinfo.Min_value))
                            {
                                nf2.MinValue = double.Parse(oinfo.Min_value);
                            }
                            if (!string.IsNullOrEmpty(oinfo.Max_value))
                            {
                                nf2.MaxValue = double.Parse(oinfo.Max_value);
                            }
                            nf2.SelectOnFocus = true;
                            field = nf2;

                        }
                        break;
                    case "boolean":
                    case "bit":
                        if (!isHeaderFilter)
                        {
                            Checkbox cb = new Checkbox();
                            cb.InputValue = "0";
                            field = cb;
                        }

                        else
                        {
                            NumberField nf2 = new NumberField();
                            nf2.AllowDecimals = false;
                            field = nf2;
                        }
                        break;
                    case "datetime":
                    case "date":
                        if (!oinfo.Editable.Value & !isHeaderFilter)
                        {
                            DisplayField dp = new DisplayField();

                            field = dp;
                        }
                        else
                        {
                            DateField df = new DateField();
                            if (!isHeaderFilter)
                                df.AllowBlank = !oinfo.Not_blank.Value;
                            if (!string.IsNullOrEmpty(oinfo.Min_value))
                            {
                                df.MinDate = DateTime.Parse(oinfo.Min_value);
                            }
                            if (!string.IsNullOrEmpty(oinfo.Max_value))
                            {
                                df.MaxDate = DateTime.Parse(oinfo.Max_value);
                            }

                            field = df;
                        }
                        break;
                }
            }
            if (!string.IsNullOrEmpty(oinfo.Option_text))
            {
                string[] multi = oinfo.Option_text.Split('|');
                string optionString = oinfo.Option_text;
                if (multi.Length > 1)
                {
                    optionString = multi[1];
                    if (multi[0] == "M")
                    {
                        MultiCombo ct = new MultiCombo();

                        string[] options = optionString.Split(',');
                        for (int i = 0; i < options.Length; i++)
                        {
                            ct.Items.Add(new ListItem(options[i], (i).ToString()));
                        }
                        field = ct;
                    }
                }
                else
                {

                    ComboBox ct = new ComboBox();
                    if (!isHeaderFilter)
                        ct.AllowBlank = !oinfo.Not_blank.Value;
                    string[] options = optionString.Split(',');
                    for (int i = 0; i < options.Length; i++)
                    {
                        ct.Items.Add(new ListItem(options[i], (i).ToString()));
                    }
                    ct.SelectOnFocus = true;
                    field = ct;
                }
            }
            if (field != null)
            {
                field.ID = inGrid == true ? Name2ID(oinfo.Name) + "Ingrid" : Name2ID(oinfo.Name);
                field.Name = Name2ID(oinfo.Name);
                if (!isHeaderFilter)
                {
                    field.ReadOnly = !oinfo.Editable.Value;
                    if (field.GetType() == typeof(Checkbox) || field.GetType() == typeof(DateField))
                        field.Disabled = !oinfo.Editable.Value;
                    field.FieldLabel = fLabel;
                }
                else
                {
                    field.FieldLabel = fLabel;
                    field.HideLabel = true;
                }
                field.EmptyValue = oinfo.Values_allowed;
                if (!inGrid)
                    field.TabIndex = (short)oinfo.Form_tab_index.Value;
                else
                    field.HideLabel = true;
                field.IDMode = IDMode.Static;


                if (!string.IsNullOrEmpty(oinfo.Extended_info))
                {
                    Set_extended_property(field, oinfo.Extended_info);
                }

            }
            return field;
        }



        /// <summary>
        /// Dùng để Build ColumnBase.
        /// </summary>
        /// <param name="oinfo">Cung cấp Object được lấy từ DB để tạo Column. </param>
        /// <param name="langID">Mã ngôn ngữ hiện thị.</param>
        /// <param name="editable">Cho phép edit</param>
        /// <returns>ColumnBase</returns>
        public ColumnBase Buil_grid_column(Object_property oinfo, string langID, bool editable)
        {
            CultureInfo cinfo = new CultureInfo(Convert.ToInt32(langID));

            string columnText = (oinfo.Caption.Replace('_', '.'));
            if (!string.IsNullOrEmpty(oinfo.Caption_ML))
            {
                JsonObject objText = JSON.Deserialize<JsonObject>(oinfo.Caption_ML);
                columnText = objText[langID].ToString();
            }
            ColumnBase cl = null;
            string type = string.IsNullOrEmpty(oinfo.Control_addIn) ? oinfo.Type.Trim().ToLower() : oinfo.Control_addIn.Trim().ToLower();
            switch (type)
            {
                case "nvarchar":
                case "varchar":
                case "char":
                    cl = new Column();
                    break;
                case "decimal":
                case "float":
                case "double":

                    NumberColumn nc = new NumberColumn();
                    nc.Format = "0" + cinfo.NumberFormat.CurrencyGroupSeparator + "000" + cinfo.NumberFormat.CurrencyDecimalSeparator + "/i";
                    // Bỏ số thập phân theo yêu cầu Defect ID 1801056    
                    //nc.Format = "0" + cinfo.NumberFormat.CurrencyGroupSeparator + "000" + cinfo.NumberFormat.CurrencyDecimalSeparator + "00/i";
                    if (!string.IsNullOrEmpty(oinfo.Auto_format_expr))
                    {
                        nc.Format = oinfo.Auto_format_expr;
                    }
                    cl = nc;
                    cl.Align = Alignment.Right;
                    break;
                case "int":
                case "bigint":
                case "smallint":
                case "tinyint":
                    if (!string.IsNullOrEmpty(oinfo.Option_text))
                    {
                        cl = new Column();
                    }
                    else
                    {
                        NumberColumn nc2 = new NumberColumn();
                        nc2.Format = "0" + cinfo.NumberFormat.CurrencyGroupSeparator + "000/i";
                        if (!string.IsNullOrEmpty(oinfo.Auto_format_expr))
                        {
                            nc2.Format = oinfo.Auto_format_expr;
                        }
                        cl = nc2;
                    }

                    break;
                case "boolean":
                case "bit":
                    CheckColumn cb = new CheckColumn();
                    if (oinfo.Editable.Value & editable)
                    {
                        cb.Editable = true;
                    }
                    cl = cb;
                    break;
                case "datetime":
                case "date":
                    DateColumn dc = new DateColumn();
                    dc.Format = cinfo.DateTimeFormat.ShortDatePattern;
                    if (!string.IsNullOrEmpty(oinfo.Auto_format_expr))
                    {
                        dc.Format = oinfo.Auto_format_expr;
                    }
                    cl = dc;
                    break;
            }
            if (cl != null)
            {
                cl.ID = Name2ID(oinfo.Name + " " + oinfo.Name);
                cl.DataIndex = Name2ID(oinfo.Name);
                cl.Text = columnText;
                cl.ToolTip = columnText;

                if (!string.IsNullOrEmpty(oinfo.Option_text))
                {
                    string[] multi = oinfo.Option_text.Split('|');
                    string optionString = oinfo.Option_text;
                    if (multi.Length > 1)
                    {
                        optionString = multi[1];
                        if (multi[0] == "M")
                        {
                            cl.Renderer.Handler += string.Format("return MultiComboRenderer(value,'{0}');", optionString);
                        }
                    }
                    else
                    {
                        cl.Renderer.Handler += string.Format("return ComboRenderer(value,'{0}');", optionString);

                    }

                }
                if (oinfo.Editable != null && oinfo.Editable == true && editable == true)
                {
                    if (cl.GetType() != typeof(CheckColumn))
                    {
                        Field fEditor = Buil_control(oinfo, langID, true);
                        fEditor.HideLabel = true;
                        fEditor.ID = fEditor.ID + "Editor";
                        cl.Editor.Add(fEditor);
                    }
                }
                if (!string.IsNullOrEmpty(oinfo.Extended_info))
                {
                    Set_extended_property(cl, oinfo.Extended_info);
                }


            }
            return cl;
        }

        /// <summary>
        /// dùng để cấu hình các field không phải field chuẩn.
        /// </summary>
        /// <param name="f">XControl of EXT</param>
        /// <param name="strExtended_property">strExtended_property</param>
        public void Set_extended_property(Field f, string strExtended_property)
        {
            try
            {
                strExtended_property = "{" + strExtended_property.TrimStart('{').TrimEnd('}') + "}";
                JsonObject oc = JSON.Deserialize<JsonObject>(strExtended_property);
                foreach (string k in oc.Keys)
                {
                    if (f.ConfigOptions.ContainsKey(k))
                    {
                        f.ConfigOptions[k] = new ConfigOption(k, new SerializationOptions(JsonMode.Raw), null, oc[k]);
                    }
                }
            }
            catch (Exception ex)
            { }
        }
        public void Set_extended_property(ColumnBase f, string strExtended_property)
        {
            try
            {
                strExtended_property = "{" + strExtended_property.TrimStart('{').TrimEnd('}') + "}";
                JsonObject oc = JSON.Deserialize<JsonObject>(strExtended_property);
                foreach (string k in oc.Keys)
                {
                    if (f.GetType().GetProperty(k) != null)
                    {
                        //f.ConfigOptions[k] = new ConfigOption(k, new SerializationOptions(JsonMode.Raw), null, oc[k]);
                        f.GetType().GetProperty(k).SetValue(f, oc[k], null);
                    }
                }
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// Dùng để format name.
        /// </summary>
        /// <param name="name">name cần format</param>
        /// <returns>name đã được format</returns>
        public static string Name2ID(string name)
        {
            name = name.Replace('[', ' ');
            name = name.Replace(']', ' ');
            name = name.Replace('(', ' ');
            name = name.Replace(')', ' ');
            name = name.Replace("%", "Percent");
            name = name.Replace('/', ' ');
            name = name.Replace('.', ' ');
            name = name.Replace('-', ' ');
            name = name.Replace('\\', ' ');
            name = name.Replace(':', ' ');
            name = name.Replace('!', ' ');
            name = name.Replace('_', ' ');
            name = name.Replace("  ", " ");
            name = name.Replace("  ", " ");
            name = name.Trim();
            name = name.Replace(' ', '_');
            return name;
        }


    }

}

